package luongvd.weather.control;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import luongvd.weather.R;
import luongvd.weather.common.Const;
import luongvd.weather.common.Utils;
import luongvd.weather.common.service.utils.NetworkUtil;
import luongvd.weather.model.dbhelper.DatabaseHandler;
import luongvd.weather.model.delegate.ServiceDelegate;
import luongvd.weather.model.entity.EntityWeather;
import luongvd.weather.model.object.ObjectCity;
import luongvd.weather.model.object.ObjectForecast;
import luongvd.weather.model.object.ObjectWeather;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("SimpleDateFormat") public class HomeActivity extends Activity implements OnClickListener{

	ImageButton ib_menu, ib_update;
	TextView name_city, date_city, tv_temp, tv_temp_max, tx_status, tv_humidity, tv_time_update;
	TextView tv_day_of_week_1, tv_day_of_week_2, tv_day_of_week_3, tv_day_of_week_4, tv_day_of_week_5, tv_day_of_week_6;
	TextView tv_day_1, tv_day_2, tv_day_3, tv_day_4, tv_day_5, tv_day_6;
	ImageView icon_weather, img_icon_1, img_icon_2, img_icon_3, img_icon_4, img_icon_5, img_icon_6;
	TextView temp_max_1, temp_max_2, temp_max_3, temp_max_4, temp_max_5, temp_max_6;
	TextView temp_min_1, temp_min_2, temp_min_3, temp_min_4, temp_min_5, temp_min_6;
	ProgressBar progressBarLoadding;
	
	ObjectWeather objectWeather;
	ObjectForecast objectForecast;
	ArrayList<ObjectForecast> arrayForecast;
	String lat, lon;
	long dt_default;
	ProgressDialog dialogLoading;
	Location myLocation;
	int requestCode = 1;
	String name_city_input;
	EntityWeather entityWeather;
	ObjectCity objectCity;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_home);
        copyDB();
        unitDB();
        unitWidget();
        setUnitWidget();
    }

	private void copyDB() {
		entityWeather = new EntityWeather(this);
		entityWeather.createDatabase();
	}

	private void setUnitWidget() {
//		objectCity = new ObjectCity();
//		objectCity = entityWeather.getInfoWeatherView();
//		String name_view = objectCity.getName();
//		
//		if(name_view != null)
//		{
//			Log.d("Luong", "============== name_view: "+name_view);
//			objectWeather = entityWeather.getInfoWeather(name_view).get(0);
//			Log.d("Luong", "============== getName_city: "+objectWeather.getName_city());
//			arrayForecast = entityWeather.getInfoForecast(name_view);
//			Log.d("Luong", "============== size arrayForecast: "+arrayForecast.size());
//			if(objectWeather.getName_city().equals("")== false && arrayForecast.size() > 0)
//			{
//				tv_time_update.setText(objectCity.getTime_update());
//				setWeather();
//				setForecast();
//			}
//		}else{
//			Log.d("Luong", "============== name_view null");
//		}
		if(NetworkUtil.checkNetWork(this))
		{
			dialogLoading = ProgressDialog.show(this, "", getString(R.string.loading_please_wait_), true);
			ib_update.setVisibility(View.GONE);
			progressBarLoadding.setVisibility(View.VISIBLE);
			
			ServiceDelegate.getWeather(lat, lon, getWeatherHandler);
		}else{
			dialogLoading = ProgressDialog.show(this, "", getString(R.string.loading_please_wait_), true);
			dialogLoading.dismiss();
			objectCity = new ObjectCity();
			objectCity = entityWeather.getInfoWeatherView();
			String name_view = objectCity.getName();
			
			if(name_view != null)
			{
				Log.d("Luong", "============== name_view: "+name_view);
				objectWeather = entityWeather.getInfoWeather(name_view).get(0);
				Log.d("Luong", "============== getName_city: "+objectWeather.getName_city());
				arrayForecast = entityWeather.getInfoForecast(name_view);
				Log.d("Luong", "============== size arrayForecast: "+arrayForecast.size());
				if(objectWeather.getName_city().equals("")== false && arrayForecast.size() > 0)
				{
					tv_time_update.setText(objectCity.getTime_update());
					setWeather();
					setForecast();
				}
			}else{
				Log.d("Luong", "============== name_view null");
			}
			Toast.makeText(getBaseContext(), getString(R.string.internet_not_connect_), Toast.LENGTH_SHORT).show();
		}
	}


	private void setWeather() {
		if(objectWeather != null)
		{
			name_city.setText(objectWeather.getName_city());
			
			date_city.setText(objectWeather.getDate_city());
			
			String name_icon = objectWeather.getIcon_weather()+".png";
			
			icon_weather.setImageBitmap(Utils.getBitmap(this, name_icon));
			
			tv_temp.setText(objectWeather.getTemp()+Const.CELSIUS);
			String temp_max_min = "";
			if(objectWeather.getTemp_min().equals(objectWeather.getTemp_max()) == false){
				temp_max_min = objectWeather.getTemp_min()+Const.CELSIUS+" - "+objectWeather.getTemp_max()+Const.CELSIUS;
			}
			tv_temp_max.setText(temp_max_min);
			
			tv_humidity.setText(objectWeather.getHumidity()+Const.PERCENT);
			
			tx_status.setText(objectWeather.getDescription_weather());
			
			//call set forecast
			if(NetworkUtil.checkNetWork(this))
			{
				ServiceDelegate.getForecast(lat, lon, getForecastHandler);
			}
		}else{
			Log.d("Luong", "----------------- objectWeather is null");
		}
	}


	private void unitDB() {
		myLocation = Utils.getMyLocation(this);
		Log.d("Luong", "----------------- myLocation: "+myLocation);
		dt_default = 0;
		lat = String.valueOf(myLocation.getLatitude());
		Log.d("Luong", "----------------- lat: "+lat);
		lon = String.valueOf(myLocation.getLongitude());
		Log.d("Luong", "----------------- lon: "+lon);
		objectWeather = new ObjectWeather();
		objectForecast = new ObjectForecast();
		arrayForecast = new ArrayList<ObjectForecast>();
	}


	private void unitWidget() {
		ib_menu = (ImageButton)findViewById(R.id.ib_menu);
		ib_menu.setOnClickListener(this);
		
		ib_update = (ImageButton)findViewById(R.id.ib_update);
		ib_update.setOnClickListener(this);
		progressBarLoadding = (ProgressBar)findViewById(R.id.progressBarLoadding);
		tv_time_update = (TextView)findViewById(R.id.tv_time_update);
		
		name_city = (TextView)findViewById(R.id.name_city);
		date_city = (TextView)findViewById(R.id.date_city);
		tv_temp = (TextView)findViewById(R.id.tv_temp);
		tv_temp_max = (TextView)findViewById(R.id.tv_temp_max);
		tx_status = (TextView)findViewById(R.id.tx_status);
		tv_humidity = (TextView)findViewById(R.id.tv_humidity);
		
		tv_day_of_week_1 = (TextView)findViewById(R.id.tv_day_of_week_1);
		tv_day_of_week_2 = (TextView)findViewById(R.id.tv_day_of_week_2);
		tv_day_of_week_3 = (TextView)findViewById(R.id.tv_day_of_week_3);
		tv_day_of_week_4 = (TextView)findViewById(R.id.tv_day_of_week_4);
		tv_day_of_week_5 = (TextView)findViewById(R.id.tv_day_of_week_5);
		tv_day_of_week_6 = (TextView)findViewById(R.id.tv_day_of_week_6);
		
		tv_day_1 = (TextView)findViewById(R.id.tv_day_1);
		tv_day_2 = (TextView)findViewById(R.id.tv_day_2);
		tv_day_3 = (TextView)findViewById(R.id.tv_day_3);
		tv_day_4 = (TextView)findViewById(R.id.tv_day_4);
		tv_day_5 = (TextView)findViewById(R.id.tv_day_5);
		tv_day_6 = (TextView)findViewById(R.id.tv_day_6);
		
		icon_weather = (ImageView)findViewById(R.id.icon_weather);
		img_icon_1 = (ImageView)findViewById(R.id.img_icon_1);
		img_icon_2 = (ImageView)findViewById(R.id.img_icon_2);
		img_icon_3 = (ImageView)findViewById(R.id.img_icon_3);
		img_icon_4 = (ImageView)findViewById(R.id.img_icon_4);
		img_icon_5 = (ImageView)findViewById(R.id.img_icon_5);
		img_icon_6 = (ImageView)findViewById(R.id.img_icon_6);
		
		temp_max_1 = (TextView)findViewById(R.id.temp_max_1);
		temp_max_2 = (TextView)findViewById(R.id.temp_max_2);
		temp_max_3 = (TextView)findViewById(R.id.temp_max_3);
		temp_max_4 = (TextView)findViewById(R.id.temp_max_4);
		temp_max_5 = (TextView)findViewById(R.id.temp_max_5);
		temp_max_6 = (TextView)findViewById(R.id.temp_max_6);
		
		temp_min_1 = (TextView)findViewById(R.id.temp_min_1);
		temp_min_2 = (TextView)findViewById(R.id.temp_min_2);
		temp_min_3 = (TextView)findViewById(R.id.temp_min_3);
		temp_min_4 = (TextView)findViewById(R.id.temp_min_4);
		temp_min_5 = (TextView)findViewById(R.id.temp_min_5);
		temp_min_6 = (TextView)findViewById(R.id.temp_min_6);
		
	}


	Handler getWeatherHandler = new Handler() {
		@SuppressLint("SimpleDateFormat") public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 0) {
				try {
					JSONObject json = new JSONObject();
					json = (JSONObject) msg.obj;
					if(json!=null)
					{
						Log.d("Luong", "---------------json: "+json);
						int cod = json.getInt(Const.KEY_COD);
						Log.d("Luong", "---------------cod: "+cod);
						if(cod == 200)
						{
							long dt = json.getLong(Const.KEY_TIME_UPDATE);
							Log.d("Luong", "------------- dt: "+dt);
							if(dt != dt_default)
							{
								dt_default = dt;
								objectWeather = new ObjectWeather();
								
								String name_city = json.getString(Const.KEY_NAME_CITY);
								Log.d("Luong", "------------- name city: "+name_city);
								objectWeather.setName_city(name_city);
								
								objectWeather.setDt_weather(String.valueOf(dt));
								String date_city = Utils.convertUnixtimeToTime(dt);
								Log.d("Luong", "------------- date_city: "+date_city);
								objectWeather.setDate_city(date_city);
								
								JSONObject weather = new JSONObject();
								weather = json.getJSONArray(Const.KEY_WEATHER).getJSONObject(0);
								
								String id_weather = weather.getString(Const.KEY_ID_WEATHER);
								Log.d("Luong", "------------- id_weather: "+id_weather);
								objectWeather.setId_weather(id_weather);
								
								String icon_weather = weather.getString(Const.KEY_ICON_WEATHER);
								Log.d("Luong", "------------- icon_weather: "+icon_weather);
								objectWeather.setIcon_weather(icon_weather);
								
								String description_weather = weather.getString(Const.KEY_DESCRIPTION);
								Log.d("Luong", "------------- description_weather: "+description_weather);
								objectWeather.setDescription_weather(description_weather);
								
								JSONObject main = json.getJSONObject(Const.KEY_MAIN);
								
								String temp = String.valueOf(Math.round(main.getDouble(Const.KEY_TEMP)));
								Log.d("Luong", "------------- temp: "+temp);
								objectWeather.setTemp(temp);
								
								String temp_max = String.valueOf(Math.round(main.getDouble(Const.KEY_TEMP_MAX)));
								Log.d("Luong", "------------- temp_max: "+temp_max);
								objectWeather.setTemp_max(temp_max);
								
								String temp_min = String.valueOf(Math.round(main.getDouble(Const.KEY_TEMP_MIN)));
								Log.d("Luong", "------------- temp_min: "+temp_min);
								objectWeather.setTemp_min(temp_min);
								
								String humidity = main.getString(Const.KEY_HUMIDITY);
								Log.d("Luong", "------------- humidity: "+humidity);
								objectWeather.setHumidity(humidity);
								
								setWeather();
							}else{
								clearLoadingDialog(true);
							}
						}else{
							clearLoadingDialog(false);
							Toast.makeText(getBaseContext(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
						}
					}else{
						clearLoadingDialog(false);
						Log.d("Luong", "------------Json is null");
						Toast.makeText(getBaseContext(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
					}
				}catch(Exception e)
				{
					
				}
			}else if (msg.arg1 == -1) {
				clearLoadingDialog(false);
				Log.d("Luong", "------------not connect to server");
				Toast.makeText(getBaseContext(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
			}
		}
	};
	
	
	Handler getForecastHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 0) {
				try {
					JSONObject json = new JSONObject();
					json = (JSONObject) msg.obj;
					if(json!=null)
					{
						Log.d("Luong", "===================== json: "+json);
						int cod = json.getInt(Const.KEY_COD);
						Log.d("Luong", "===================== cod: "+cod);
						if(cod == 200)
						{
							arrayForecast = new ArrayList<ObjectForecast>();
							
							JSONArray jsonListForecast = json.getJSONArray(Const.KEY_LIST);
							Log.d("Luong", "===================== jsonListForecast size: "+jsonListForecast.length());
							
							for(int i=1; i< jsonListForecast.length(); i++)
							{
								objectForecast = new ObjectForecast();
								JSONObject jsonObjectForecast = jsonListForecast.getJSONObject(i);
								long dt = jsonObjectForecast.getLong(Const.KEY_TIME_UPDATE);
								objectForecast.setDt_forecast(String.valueOf(dt));
								Log.d("Luong", "===================== dt: "+dt);
								
								String day_of_week = Utils.convertUnixtimeToDayOfWeek(dt);
								objectForecast.setDay_of_week(day_of_week);
								Log.d("Luong", "===================== day_of_week: "+day_of_week);
								
								String day_of_month = Utils.convertUnixtimeToDayOfMonth(dt);
								objectForecast.setDay_of_month(day_of_month);
								Log.d("Luong", "===================== day_of_month: "+day_of_month);
								
								JSONObject temp = jsonObjectForecast.getJSONObject(Const.KEY_TEMP);
								String temp_max = String.valueOf(Math.round(temp.getDouble(Const.KEY_MAX)));
								objectForecast.setTemp_max(temp_max);
								Log.d("Luong", "===================== temp_max: "+temp_max);
								
								String temp_min = String.valueOf(Math.round(temp.getDouble(Const.KEY_MIN)));
								objectForecast.setTemp_min(temp_min);
								Log.d("Luong", "===================== temp_min: "+temp_min);
								
								JSONObject weather = jsonObjectForecast.getJSONArray(Const.KEY_WEATHER).getJSONObject(0);
								String icon = weather.getString(Const.KEY_ICON_WEATHER);
								objectForecast.setIcon(icon);
								Log.d("Luong", "===================== icon: "+icon);
								
								String id_weather = weather.getString(Const.KEY_ID_WEATHER);
								objectForecast.setId_weather(id_weather);
								Log.d("Luong", "===================== id_weather: "+id_weather);
								
								arrayForecast.add(objectForecast);
							}
							setForecast();
							clearLoadingDialog(true);
							saveDBClient();
						}else{
							clearLoadingDialog(false);
							Toast.makeText(getBaseContext(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
						}
					}else{
						clearLoadingDialog(false);
						Log.d("Luong", "===================== Json is null");
						Toast.makeText(getBaseContext(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
					}
				}catch(Exception e)
				{
					
				}
			}else if (msg.arg1 == -1) {
				clearLoadingDialog(false);
				Log.d("Luong", "===================== not connect to server");
				Toast.makeText(getBaseContext(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
			}
		}
	};
	
	private void saveDBClient(){
		//save to db client
		DatabaseHandler.deleteRowWeatherByName(objectWeather.getName_city());
		DatabaseHandler.deleteRowForecastByName(objectWeather.getName_city());
		DatabaseHandler.deleteRowWeatherView();
		DatabaseHandler.addWeatherView(objectWeather.getName_city(),tv_time_update.getText().toString());
		DatabaseHandler.addWeather(objectWeather.getDt_weather(), objectWeather.getDate_city(), objectWeather.getName_city(), objectWeather.getIcon_weather(), objectWeather.getTemp(), objectWeather.getTemp_max(), objectWeather.getTemp_min(), objectWeather.getHumidity(), objectWeather.getDescription_weather());
		Log.d("Luong", "========================== size arrayForecast insert:"+arrayForecast.size());
		for(int i=0; i< arrayForecast.size(); i++)
		{
			ObjectForecast objectForcast = arrayForecast.get(i);
			DatabaseHandler.addForecast(objectWeather.getDt_weather(), objectWeather.getName_city(), objectForcast.getDay_of_week(), objectForcast.getDay_of_month(), objectForcast.getIcon(), objectForcast.getTemp_max(), objectForcast.getTemp_min());
		}
	}
	
	
	private void setForecast() {
		Log.d("Luong", "===================== arrayForecast size llllllllllllll: "+arrayForecast.size());
		ObjectForecast obForecast = new ObjectForecast();
		obForecast = arrayForecast.get(0);
		tv_day_of_week_1.setText(obForecast.getDay_of_week());
		tv_day_1.setText(obForecast.getDay_of_month());
		temp_max_1.setText(obForecast.getTemp_max()+Const.CELSIUS);
		temp_min_1.setText(obForecast.getTemp_min()+Const.CELSIUS);
		img_icon_1.setImageBitmap(Utils.getBitmap(this, obForecast.getIcon()+".png"));
		
		obForecast = arrayForecast.get(1);
		tv_day_of_week_2.setText(obForecast.getDay_of_week());
		tv_day_2.setText(obForecast.getDay_of_month());
		temp_max_2.setText(obForecast.getTemp_max()+Const.CELSIUS);
		temp_min_2.setText(obForecast.getTemp_min()+Const.CELSIUS);
		img_icon_2.setImageBitmap(Utils.getBitmap(this, obForecast.getIcon()+".png"));
		
		obForecast = arrayForecast.get(2);
		tv_day_of_week_3.setText(obForecast.getDay_of_week());
		tv_day_3.setText(obForecast.getDay_of_month());
		temp_max_3.setText(obForecast.getTemp_max()+Const.CELSIUS);
		temp_min_3.setText(obForecast.getTemp_min()+Const.CELSIUS);
		img_icon_3.setImageBitmap(Utils.getBitmap(this, obForecast.getIcon()+".png"));
		
		obForecast = arrayForecast.get(3);
		tv_day_of_week_4.setText(obForecast.getDay_of_week());
		tv_day_4.setText(obForecast.getDay_of_month());
		temp_max_4.setText(obForecast.getTemp_max()+Const.CELSIUS);
		temp_min_4.setText(obForecast.getTemp_min()+Const.CELSIUS);
		img_icon_4.setImageBitmap(Utils.getBitmap(this, obForecast.getIcon()+".png"));
		
		obForecast = arrayForecast.get(4);
		tv_day_of_week_5.setText(obForecast.getDay_of_week());
		tv_day_5.setText(obForecast.getDay_of_month());
		temp_max_5.setText(obForecast.getTemp_max()+Const.CELSIUS);
		temp_min_5.setText(obForecast.getTemp_min()+Const.CELSIUS);
		img_icon_5.setImageBitmap(Utils.getBitmap(this, obForecast.getIcon()+".png"));
		
		obForecast = arrayForecast.get(5);
		tv_day_of_week_6.setText(obForecast.getDay_of_week());
		tv_day_6.setText(obForecast.getDay_of_month());
		temp_max_6.setText(obForecast.getTemp_max()+Const.CELSIUS);
		temp_min_6.setText(obForecast.getTemp_min()+Const.CELSIUS);
		img_icon_6.setImageBitmap(Utils.getBitmap(this, obForecast.getIcon()+".png"));
	}
	
	private void clearLoadingDialog(Boolean setDateUpdate){
		dialogLoading.dismiss();
		ib_update.setVisibility(View.VISIBLE);
		progressBarLoadding.setVisibility(View.GONE);
		if(setDateUpdate == true)
		{
			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
			String currentDateandTime = sdf.format(new Date());
			tv_time_update.setText(currentDateandTime);
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ib_menu:
			//convert object to json
//			Gson gson = new Gson();
//			String jsonObjectWeather = gson.toJson(objectWeather);
			
			Intent intent = new Intent(this, AddCityActivity.class);
//			intent.putExtra(Const.KEY_JSON_WEATHER, jsonObjectWeather);
//			intent.putExtra(Const.KEY_TIME_UPDATE, dt_default);
//			intent.putExtra(Const.KEY_LAT, lat);
//			intent.putExtra(Const.KEY_LON, lon);
			startActivity(intent);
			break;
		case R.id.ib_update:
			if(NetworkUtil.checkNetWork(this))
			{
				dialogLoading.show();
				ib_update.setVisibility(View.GONE);
				progressBarLoadding.setVisibility(View.VISIBLE);
				
				ServiceDelegate.getWeather(lat, lon, getWeatherHandler);
			}else{
				Toast.makeText(getBaseContext(), getString(R.string.internet_not_connect_), Toast.LENGTH_SHORT).show();
			}
			break;

		default:
			break;
		}
		
	}

}
